Telegram Group & Telegram Channel
std::span — мощная альтернатива std::vector и std::array

Сегодня поговорим о std::span — контейнере, который делает работу с массивами и векторами в C++ более удобной и эффективной. 🚀

Проблема: Лишние копии данных
Представьте, что у нас есть функция, принимающая массив чисел:


void processArray(const std::vector<int>& arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}


С одной стороны, передача const std::vector<int>& предотвращает копирование, но что, если у нас массив std::array или сырой int[]?
Придётся перегружать функцию или копировать данные в std::vector.

Решение: Используем std::span
std::span позволяет передавать любой диапазон (`std::vector`, std::array, сырые массивы) без копирования:


#include <iostream>
#include <span>
#include <vector>
#include <array>

void processArray(std::span<int> arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}

int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::array<int, 5> arr = {6, 7, 8, 9, 10};
int rawArr[] = {11, 12, 13, 14, 15};

processArray(vec); // Работает
processArray(arr); // Работает
processArray(rawArr); // Работает
}


🚀 Преимущества std::span
Не копирует данные — передаётся как ссылка
Работает с любыми последовательностями
Гибкость — можно создавать срезы без копий

Пример использования .subspan(), чтобы передавать часть массива:


std::vector<int> vec = {1, 2, 3, 4, 5};
std::span<int> sp = vec;
processArray(sp.subspan(2)); // Выведет: 3 4 5


⚠️ Важно
- std::span не владеет данными. Убедитесь, что исходные данные живут дольше span.
- Не поддерживает автоматическое изменение размера, как std::vector.

📌 Итог
Если ваша функция принимает std::vector<int>&, std::array<int, N>&, int[] или даже std::initializer_list<int>, замените их на std::span<int>! Это сделает код более гибким и эффективным. 🔥

➡️ @cpp_geek



tg-me.com/cpp_geek/288
Create:
Last Update:

std::span — мощная альтернатива std::vector и std::array

Сегодня поговорим о std::span — контейнере, который делает работу с массивами и векторами в C++ более удобной и эффективной. 🚀

Проблема: Лишние копии данных
Представьте, что у нас есть функция, принимающая массив чисел:


void processArray(const std::vector<int>& arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}


С одной стороны, передача const std::vector<int>& предотвращает копирование, но что, если у нас массив std::array или сырой int[]?
Придётся перегружать функцию или копировать данные в std::vector.

Решение: Используем std::span
std::span позволяет передавать любой диапазон (`std::vector`, std::array, сырые массивы) без копирования:


#include <iostream>
#include <span>
#include <vector>
#include <array>

void processArray(std::span<int> arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}

int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::array<int, 5> arr = {6, 7, 8, 9, 10};
int rawArr[] = {11, 12, 13, 14, 15};

processArray(vec); // Работает
processArray(arr); // Работает
processArray(rawArr); // Работает
}


🚀 Преимущества std::span
Не копирует данные — передаётся как ссылка
Работает с любыми последовательностями
Гибкость — можно создавать срезы без копий

Пример использования .subspan(), чтобы передавать часть массива:


std::vector<int> vec = {1, 2, 3, 4, 5};
std::span<int> sp = vec;
processArray(sp.subspan(2)); // Выведет: 3 4 5


⚠️ Важно
- std::span не владеет данными. Убедитесь, что исходные данные живут дольше span.
- Не поддерживает автоматическое изменение размера, как std::vector.

📌 Итог
Если ваша функция принимает std::vector<int>&, std::array<int, N>&, int[] или даже std::initializer_list<int>, замените их на std::span<int>! Это сделает код более гибким и эффективным. 🔥

➡️ @cpp_geek

BY C++ geek


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpp_geek/288

View MORE
Open in Telegram


C geek Telegram | DID YOU KNOW?

Date: |

How to Buy Bitcoin?

Most people buy Bitcoin via exchanges, such as Coinbase. Exchanges allow you to buy, sell and hold cryptocurrency, and setting up an account is similar to opening a brokerage account—you’ll need to verify your identity and provide some kind of funding source, such as a bank account or debit card. Major exchanges include Coinbase, Kraken, and Gemini. You can also buy Bitcoin at a broker like Robinhood. Regardless of where you buy your Bitcoin, you’ll need a digital wallet in which to store it. This might be what’s called a hot wallet or a cold wallet. A hot wallet (also called an online wallet) is stored by an exchange or a provider in the cloud. Providers of online wallets include Exodus, Electrum and Mycelium. A cold wallet (or mobile wallet) is an offline device used to store Bitcoin and is not connected to the Internet. Some mobile wallet options include Trezor and Ledger.

What Is Bitcoin?

Bitcoin is a decentralized digital currency that you can buy, sell and exchange directly, without an intermediary like a bank. Bitcoin’s creator, Satoshi Nakamoto, originally described the need for “an electronic payment system based on cryptographic proof instead of trust.” Each and every Bitcoin transaction that’s ever been made exists on a public ledger accessible to everyone, making transactions hard to reverse and difficult to fake. That’s by design: Core to their decentralized nature, Bitcoins aren’t backed by the government or any issuing institution, and there’s nothing to guarantee their value besides the proof baked in the heart of the system. “The reason why it’s worth money is simply because we, as people, decided it has value—same as gold,” says Anton Mozgovoy, co-founder & CEO of digital financial service company Holyheld.

C geek from kr


Telegram C++ geek
FROM USA